<template>
  <div class="warpper-box">
    <a-row :gutter="24">
      <a-col :span="6">
        <a-card :bordered="true" :style="{ height: '100%' }">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <a-select v-model="enterpriseId" @change="enterpriseChange" style="width: 200px;" show-search :filter-option="filterOption"
              :disabled="userInfo.type == 5">
              <a-select-option v-for="item in enterpriseData" :key="item.enterpriseId" :name="item.name">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <span>
              <a-icon @click="backMenu()" class="link-icon" type="sync" style="margin-right: 10px;" />
              <a-icon @click="add(-1, 'add')" class="link-icon" type="plus-circle" />
            </span>
          </div>
          <a-tree defaultExpandAll :tree-data="treeData" class="orgListTree">
            <template v-slot:title="nodeData">
              <div style="width: 100%;display: flex;justify-content: space-between;align-items: center;">
                <span style="width: 100%;text-overflow: ellipsis;overflow: hidden;" @click="checkTree(nodeData)" :title="nodeData.orgName">{{ nodeData.orgName }}</span>
                <span style="margin-left:10px;flex-shrink: 0;">
                  <a-button type="link" icon="plus-circle" @click="() => add(nodeData, 'add')"></a-button>
                  <a-button type="link" icon="form" @click="() => add(nodeData, 'edit')"></a-button>
                  <a-popconfirm title="删除后，不能恢复，确认删除！" ok-text="确认" cancel-text="取消" @confirm="remove(nodeData.orgId)">
                    <a-button type="link" icon="delete"></a-button>
                  </a-popconfirm>
                </span>
              </div>
            </template>
          </a-tree>
          <a-empty v-show="treeData.length === 0" style="margin: 50px auto;" />
        </a-card>
      </a-col>
      <a-col :span="18">
        <a-form layout="inline">
          <a-form-item label="组织名称">
            <a-input placeholder="组织名称" v-model="orgName"></a-input>
          </a-form-item>
          <a-form-item label="组织编码">
            <a-input placeholder="组织编码" v-model="orgCode"></a-input>
          </a-form-item>
          <a-form-item>
            <a-button type='primary' @click="initMenuList(true)">查询</a-button>
          </a-form-item>
        </a-form>
        <a-table :columns="table.columns" :data-source="table.loadData" :pagination="table.pagination"
          @change="handleTableChange" rowKey="id">

        </a-table>
      </a-col>
    </a-row>
    <a-modal :title="title" :width="640" :visible="visible" @ok="handleOk" @cancel="visible = false">
      <div v-if="treeData.length > 0">
        <a-form-item label="上级部门">
          <a-tree-select showSearch treeNodeFilterProp="title" style="width:100%" :tree-data="treeData" :replace-fields="{'key': 'orgId','label': 'orgName', 'children': 'children'}" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" v-model="menuParent">
          </a-tree-select>
        </a-form-item>
      </div>
      <form-create v-model="form.fApi" :rule="form.rule" :option="form.option" />
    </a-modal>
  </div>
</template>

<script>


import store from '@/store'
import {
  orgGetMenuTree,
  orgQueryMenuIdChildList,
  orgMenuDisable,
  orgAddMenu,
  orgEidtMenu,
  orgDelMenu
} from '@/api/human/relationOrg'
import {
  FORM_PARENT_MENU,
  MENU_COLUMNS,
  OPTION_BLOCK
} from './form'
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'MenuList',
  components: {

  },
  data() {
    return {
      form: {
        fApi: {},
        rule: [],
        option: OPTION_BLOCK
      },
      visible: false,
      title: '父级',
      id: '',
      menuParent: '',
      menuParentName: '',
      menuId: '',
      treeData: [],

      orgName: "", // 表格组织名称
      orgCode: "", // 表格组织编码
      table: { // 表格数据项
        columns: MENU_COLUMNS,
        loadData: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      pagination: { current: 1, pageSize: 10 },

      enterpriseId: "",
      enterpriseData: [],
    }
  },
  mounted() {

  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {
    this.getEnterpriseData();
  },
  methods: {
    add(row, type) {
      // console.log(row);
      this.form.rule = FORM_PARENT_MENU;
      this.$nextTick(() => {
        this.form.fApi.resetFields();
      });
      if (type === 'add') {
        this.id = '';
        if (row !== -1) {
          this.menuParent = row.orgId
          this.menuParentName = row.orgName
        } else {
          // 最顶层新增
          this.menuParent = this.enterpriseId
          this.menuParentName = this.menuParentName
        }
        this.title = row === -1 ? '新增组织' : '新增组织';
      } else {
        this.id = row.orgId;
        this.menuParent = row.parentOrgId;
        this.menuParentName = row.parentOrgName
        this.title = '编辑组织';
        this.$nextTick(() => {
          this.form.fApi.setValue({
            name: row.orgName
          })
        })
      }
      this.visible = true;
    },
    // 获取部门数据
    async initMenuTree() {
      this.orgName = '';
      this.orgCode = '';
      const { code, data } = await orgGetMenuTree(this.enterpriseId);
      if (code === '1') {
        this.treeData = data;
        this.initMenuList(true)
      }
    },
    // 获取部门数据列表
    async initMenuList(flag) {
      let params = {
        parentOrgId: this.menuId,
        name: this.orgName,
        orgCode: this.orgCode
      };
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await orgQueryMenuIdChildList(params);
      if (code === '1') {
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.initMenuList(false);
    },
    // 返回顶层菜单列表
    backMenu() {
      this.menuId = this.enterpriseId;
      this.initMenuList(true);
    },
    // 获取客户员工
    async getEnterpriseData() {
      this.enterpriseData = await store.dispatch('department/getAllEnterprise');
      this.enterpriseId = this.enterpriseData[0].enterpriseId
      this.menuId = this.enterpriseData[0].enterpriseId
      this.menuParentName = this.enterpriseData[0].name
      this.initMenuTree();
    },
    // 选择客户
    enterpriseChange(value, option) {
      this.enterpriseId = value
      this.menuId = value
      this.menuParentName = option.data.attrs.name
      this.initMenuTree();
    },
    checkTree(checkedNodes) {
      this.menuId = checkedNodes.orgId;
      this.initMenuList(true);
    },
    async remove(id) {
      const { code } = await orgDelMenu({ orgId: id });
      if (code === '1') {
        this.$message.success('操作成功');

        this.initMenuTree();
        this.initMenuList(true);
      }
    },
    // 检索搜索
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    handleOk() {
      this.form.fApi.submit(async (formData, $f) => {
        try {
          if (this.id) {
            formData.orgId = this.id;
          } else {
            formData.enterpriseId = this.enterpriseId;
          }
          formData.parentOrgId = this.menuParent;
          // formData.parentOrgName = this.menuParentName;
          const { code } = this.id ? await orgEidtMenu(formData) : await orgAddMenu(formData);
          if (code === '1') {
            this.initMenuTree();
            this.visible = false;
          }
        } catch (error) {
          this.$message.info(JSON.stringify(error));
        }
      })
    }
  }
}
</script>
<style lang="less">
.orgListTree{
  .ant-tree-node-content-wrapper {
    width: 100%;
  }
}
</style>

